package com.maibow.controller.admin;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.exception.BusinessException;
import com.maibow.service.admin.DictionaryService;
import com.maibow.service.admin.SystemMessageService;
import com.maibow.service.organ.OrganService;
import com.maibow.service.system.CommonService;
import com.maibow.util.CommonConstants;
import com.maibow.util.DateUtil;
import com.maibow.util.FileUpload;
import com.maibow.util.PageData;
import com.maibow.util.PathUtil;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.admin
 * 文件名：SystemMessageController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年11月14日-上午10:14:39
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/systemMessage")
public class SystemMessageController extends BaseController {

    @Resource(name = "systemMessageService")
    private SystemMessageService systemMessageService;

    @Resource(name = "commonService")
    private CommonService commonService;

    @Resource(name = "organService")
    private OrganService organService;

    @Resource(name = "dictionaryService")
    private DictionaryService dictionaryService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    public ModelAndView querySystemMessagelistPage(HttpSession session, Page page) throws Exception {
        logBefore(logger, "活动列表");
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();

        try {
            pageData = this.getPageData();
            List<PageData> varList = systemMessageService.querySystemMessagelistPage(page);
            modelView.setViewName("system/admin/system_message_list");
            modelView.addObject("varList", varList);
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        return modelView;
    }

    /**
     * 去新增页面
     * 
     * @throws BusinessException
     */
    @RequestMapping(value = "/goAddSystemMessage")
    public ModelAndView goAddSystemMessage() throws BusinessException {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        modelView.addObject("pageData", pageData);
        modelView.setViewName("system/admin/system_message_add");
        return modelView;
    }

    /**
     * 去修改页面
     */
    @RequestMapping(value = "/goEditSystemMessage")
    public ModelAndView goEditSystemMessage() {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        try {
            pageData.put("system_message_id", Integer.valueOf(pageData.get("system_message_id").toString()));
            pageData = systemMessageService.findSystemMessageById(pageData);
            modelView.setViewName("system/admin/system_message_edit");
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/saveSystemMessage")
    public ModelAndView save(HttpServletRequest request, @RequestParam(value = "system_img", required = false) MultipartFile system_img,
                        @RequestParam(value = "organid", required = false) String organid, @RequestParam(value = "description", required = false) String description) throws Exception {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        processImage(pageData, system_img, "system_img", "");
        pageData.put("description", description);
        pageData.put("create_date", DateUtil.formatTime(DateUtil.getTime())); // 新增时间
        systemMessageService.saveSystemMessage(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/editSystemMessage")
    public ModelAndView edit(HttpServletRequest request, @RequestParam(value = "system_img", required = false) MultipartFile system_img,
                        @RequestParam(value = "system_imghidden", required = false) String system_imghidden, @RequestParam(value = "system_message_id", required = false) String system_message_id,
                        @RequestParam(value = "description", required = false) String description) throws Exception {
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        pageData = this.getPageData();
        if (null == system_imghidden) {
            system_imghidden = "";
        }
        pageData.put("system_message_id", Integer.valueOf(system_message_id));
        pageData.put("description", description);
        processImage(pageData, system_img, "system_img", system_imghidden);
        systemMessageService.editSystemMessage(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/deleteSystemMessage")
    public void delete(PrintWriter out) throws Exception {
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            pageData.put("system_message_id", Integer.valueOf(pageData.get("system_message_id").toString()));
            pageData = systemMessageService.findSystemMessageById(pageData); // 通过ID获取数据

            String system_img = pageData.getString("system_img");

            // 删除硬盘上的文件 start
            String xmpath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../"; // 项目路径
            if (system_img != null && !system_img.equals("")) {
                system_img = (xmpath.trim() + system_img.trim()).substring(6).trim();
                File f1 = new File(system_img.trim());
                if (f1.exists()) {
                    f1.delete();
                } else {
                    logger.debug("====" + system_img + "不存在");
                }
            }

            systemMessageService.deleteSystemMessageById(pageData);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    private void processImage(PageData pageData, MultipartFile imageurl, String key, String imageurlhidden) {
        String ffile = DateUtil.getDays(), fileName = "";
        String filePath = null;
        if (null != imageurl && !imageurl.isEmpty()) {
            filePath = PathUtil.getUploadImagePath() + CommonConstants.FILEPATHIMG + ffile + "_system_message/"; // 文件上传路径
            fileName = FileUpload.fileUp(imageurl, filePath, this.get32UUID()); // 执行上传
            String imageurlstr = CommonConstants.FILEPATHIMG + ffile + "_system_message/" + fileName;

            pageData.put(key, imageurlstr);
        } else {
            pageData.put(key, imageurlhidden);
        }
    }

    // 删除图片
    @ResponseBody
    @RequestMapping(value = "/deltp/{url1}/{url2}/{url3}/{tpurl}/{target}/{system_message_id}", method = RequestMethod.POST)
    public ModelAndView deltp(@PathVariable String url1, @PathVariable String url2, @PathVariable String url3, @PathVariable String tpurl, @PathVariable String target,
                        @PathVariable String system_message_id, HttpServletRequest request, HttpServletResponse response) {
        logBefore(logger, "删除图片");
        ModelAndView modelView = new ModelAndView();
        String msg = null;
        try {
            PageData pageData = new PageData();
            pageData = this.getPageData();
            pageData.put("system_message_id", Integer.valueOf(system_message_id));
            pageData.put("target", target);

            // 图片路径
            if (tpurl != null) {
                // 删除硬盘上的文件 start
                String xmpath = PathUtil.getUploadImagePath(); // 项目路径
                tpurl = xmpath.trim() + url1 + "/" + url2 + "/" + url3 + "/" + tpurl;

                // 'file:/'
                File f = new File(tpurl.trim());
                if (f.exists()) {
                    f.delete();
                } else {
                    logger.debug("图片不存在");
                }
                // 删除硬盘上的文件 end
                systemMessageService.delTp(pageData); // 删除数据中图片数据
            }

            msg = "success";
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        modelView.addObject(msg);
        return modelView;
    }
}
